<?php
/**
 * Created by PhpStorm.
 * User: fujianguo
 * Date: 2017/3/14
 * Time: 下午6:47
 */

namespace app\models\behaviors;


use app\models\db\Article;
use yii\base\Behavior;
use app\models\db\TagHasArticle;
use app\models\db\Tag;

class TagBehavior extends Behavior
{
    public function events()
    {
        return [
            Article::EVENT_BEFORE_VALIDATE=>'replaceKeyword',
            Article::EVENT_AFTER_INSERT => 'addTags',
            Article::EVENT_BEFORE_UPDATE => 'addTags',
        ];
    }

    public function replaceKeyword() {
        $article = $this->owner;
        /**@var Article $article **/
        $article->keyWord = trim(str_replace(['，',' ','|'],',',$article->keyWord),',');
    }

    public function addTags()
    {
        $article = $this->owner;
        /**@var Article $article **/
        $tags = explode(',',$article->keyWord);
        TagHasArticle::deleteAll(['article_id'=>$article->id]);
        foreach ($tags as $tag) {
            $article->addTag($tag);
        }
    }
    protected $allowTypes = ['object','integer','string'];
    public function addTag($tag)
    {
        if (!$tag) return;
        $type = gettype($tag);
        if (!in_array($type,$this->allowTypes)) throw new Exception('参数类型不正确');
        $method = 'get_'.$type.'_tag';
        $tag = $this->$method($tag);
        if (!$this->hasTag($tag->tag_name)) $this->owner->link('tags',$tag,['tag_name'=>$tag->tag_name]);
    }

    protected function hasTag($tagName)
    {
        return TagHasArticle::find()->andWhere(['article_id'=>$this->owner->id,'tag_name'=>$tagName])->exists();
    }

    protected function get_string_tag($tag)
    {
        $tagName = $tag;
        $tag = Tag::findOne(['tag_name'=>$tagName]);
        $tag = $tag?:new Tag(['tag_name'=>$tagName]);
        if(!$tag->save()) throw new Exception('Tag保存失败');
        return $tag;
    }
    protected function get_integer_tag($tag)
    {
        $tag = Tag::findOne($tag);
        if (!$tag) throw new NotFoundHttpException('没找到相应的Tag');
        return $tag;
    }
    protected function get_object_tag($tag)
    {
        if (! $tag instanceof Tag) {

            throw new NotFoundHttpException('没找到相应的Tag');
        }
        return $tag;
    }

    public function delTag(Tag $tag)
    {

    }
}